<template>
  <div class="auth-page">
    <div class="auth-container">
      <div class="auth-header">
        <div class="logo">
          <el-icon size="48" color="#FF8C00">
            <Shop />
          </el-icon>
          <h1>宠物商城</h1>
        </div>
        <div class="auth-tabs">
          <div 
            class="tab-item"
            :class="{ active: mode === 'login' }"
            @click="switchMode('login')"
          >
            登录
          </div>
          <div 
            class="tab-item"
            :class="{ active: mode === 'register' }"
            @click="switchMode('register')"
          >
            注册
          </div>
        </div>
      </div>

      <div class="auth-content">
        <!-- 登录表单 -->
        <div v-if="mode === 'login'" class="auth-form">
          <h2>欢迎回来</h2>
          <p class="form-subtitle">登录您的账户，继续购物之旅</p>
          
          <el-form 
            ref="loginFormRef"
            :model="loginForm" 
            :rules="loginRules"
            size="large"
            @submit.prevent="handleLogin"
          >
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名/手机号/邮箱"
                :prefix-icon="User"
              />
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            
            <el-form-item>
              <div class="form-options">
                <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
                <el-link type="primary" @click="showForgotPassword">忘记密码？</el-link>
              </div>
            </el-form-item>
            
            <el-form-item>
              <el-button 
                type="primary" 
                size="large"
                style="width: 100%"
                :loading="isLoading"
                @click="handleLogin"
              >
                登录
              </el-button>
            </el-form-item>
          </el-form>
          
          <div class="auth-footer">
            <span>还没有账户？</span>
            <el-link type="primary" @click="switchMode('register')">立即注册</el-link>
          </div>
        </div>

        <!-- 注册表单 -->
        <div v-else class="auth-form">
          <h2>创建账户</h2>
          <p class="form-subtitle">注册新账户，开启宠物购物体验</p>
          
          <el-form 
            ref="registerFormRef"
            :model="registerForm" 
            :rules="registerRules"
            size="large"
            @submit.prevent="handleRegister"
          >
            <el-form-item prop="username">
              <el-input
                v-model="registerForm.username"
                placeholder="请输入用户名"
                :prefix-icon="User"
              />
            </el-form-item>
            
            <el-form-item prop="phone">
              <el-input
                v-model="registerForm.phone"
                placeholder="请输入手机号"
                :prefix-icon="Phone"
              />
            </el-form-item>
            
            <el-form-item prop="email">
              <el-input
                v-model="registerForm.email"
                placeholder="请输入邮箱"
                :prefix-icon="Message"
              />
            </el-form-item>
            
            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                type="password"
                placeholder="请输入密码"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                type="password"
                placeholder="请再次输入密码"
                :prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            
            <el-form-item prop="agreement">
              <el-checkbox v-model="registerForm.agreement">
                我已阅读并同意
                <el-link type="primary" @click="showTerms">《用户协议》</el-link>
                和
                <el-link type="primary" @click="showPrivacy">《隐私政策》</el-link>
              </el-checkbox>
            </el-form-item>
            
            <el-form-item>
              <el-button 
                type="primary" 
                size="large"
                style="width: 100%"
                :loading="isLoading"
                @click="handleRegister"
              >
                注册
              </el-button>
            </el-form-item>
          </el-form>
          
          <div class="auth-footer">
            <span>已有账户？</span>
            <el-link type="primary" @click="switchMode('login')">立即登录</el-link>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { store } from '@/store'
import { 
  Shop,
  User, 
  Lock, 
  Phone, 
  Message
} from '@element-plus/icons-vue'

export default {
  name: 'AuthPage',
  components: {
    Shop,
    User,
    Lock,
    Phone,
    Message
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    
    // 响应式数据
    const mode = ref('login') // login | register
    const isLoading = ref(false)
    const loginFormRef = ref()
    const registerFormRef = ref()
    
    // 登录表单
    const loginForm = reactive({
      username: '',
      password: '',
      remember: false
    })
    
    // 注册表单
    const registerForm = reactive({
      username: '',
      phone: '',
      email: '',
      password: '',
      confirmPassword: '',
      agreement: false
    })
    
    // 验证规则
    const loginRules = {
      username: [
        { required: true, message: '请输入用户名/手机号/邮箱', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ]
    }
    
    const registerRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在3到20个字符', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/, message: '用户名只能包含中文、英文、数字和下划线', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' },
        { pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: '密码必须包含字母和数字', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== registerForm.password) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      agreement: [
        {
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请阅读并同意用户协议和隐私政策'))
            } else {
              callback()
            }
          },
          trigger: 'change'
        }
      ]
    }
    
    // 方法
    const switchMode = (newMode) => {
      mode.value = newMode
      
      // 清空表单数据
      if (newMode === 'login') {
        Object.assign(loginForm, {
          username: '',
          password: '',
          remember: false
        })
      } else if (newMode === 'register') {
        Object.assign(registerForm, {
          username: '',
          phone: '',
          email: '',
          password: '',
          confirmPassword: '',
          agreement: false
        })
      }
      
      // 更新路由查询参数
      router.replace({ query: { mode: newMode } })
    }
    
    const handleLogin = async () => {
      if (!loginFormRef.value) return
      
      try {
        await loginFormRef.value.validate()
        isLoading.value = true
        
        // 模拟登录API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 模拟登录成功
        const userData = {
          id: Date.now(),
          username: loginForm.username,
          avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${loginForm.username}`,
          phone: '138****5678',
          email: `${loginForm.username}@example.com`,
          vipLevel: Math.floor(Math.random() * 5) + 1,
          points: Math.floor(Math.random() * 10000),
          loginTime: new Date().toISOString()
        }
        
        // 保存到store和localStorage
        store.login(userData, loginForm.remember)
        
        ElMessage.success('登录成功！')
        
        // 重定向到之前的页面或首页
        const redirect = route.query.redirect || '/'
        router.push(redirect)
        
      } catch (error) {
        console.error('登录失败:', error)
      } finally {
        isLoading.value = false
      }
    }
    
    const handleRegister = async () => {
      if (!registerFormRef.value) return
      
      try {
        await registerFormRef.value.validate()
        isLoading.value = true
        
        // 模拟注册API调用
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        // 检查用户名是否已存在（模拟）
        const existingUsers = JSON.parse(localStorage.getItem('registeredUsers') || '[]')
        if (existingUsers.some(u => u.username === registerForm.username)) {
          throw new Error('用户名已存在')
        }
        
        if (existingUsers.some(u => u.phone === registerForm.phone)) {
          throw new Error('手机号已被注册')
        }
        
        if (existingUsers.some(u => u.email === registerForm.email)) {
          throw new Error('邮箱已被注册')
        }
        
        // 创建新用户
        const newUser = {
          id: Date.now(),
          username: registerForm.username,
          phone: registerForm.phone,
          email: registerForm.email,
          password: registerForm.password, // 实际应用中应该加密
          avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${registerForm.username}`,
          vipLevel: 1,
          points: 100, // 新用户赠送积分
          registerTime: new Date().toISOString()
        }
        
        // 保存到localStorage
        existingUsers.push(newUser)
        localStorage.setItem('registeredUsers', JSON.stringify(existingUsers))
        
        ElMessage.success('注册成功！请登录您的账户')
        
        // 切换到登录模式（不自动填充用户名）
        switchMode('login')
        
        // 重置注册表单
        Object.assign(registerForm, {
          username: '',
          phone: '',
          email: '',
          password: '',
          confirmPassword: '',
          agreement: false
        })
        
      } catch (error) {
        ElMessage.error(error.message || '注册失败，请重试')
      } finally {
        isLoading.value = false
      }
    }
    
    const showForgotPassword = () => {
      ElMessageBox.prompt('请输入您的邮箱', '忘记密码', {
        confirmButtonText: '发送重置邮件',
        cancelButtonText: '取消',
        inputPattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
        inputErrorMessage: '请输入正确的邮箱格式'
      }).then(({ value }) => {
        ElMessage.success(`密码重置邮件已发送到 ${value}`)
      }).catch(() => {
        // 用户取消
      })
    }
    
    const showTerms = () => {
      ElMessageBox.alert('这里是用户协议的内容...', '用户协议', {
        confirmButtonText: '我知道了'
      })
    }
    
    const showPrivacy = () => {
      ElMessageBox.alert('这里是隐私政策的内容...', '隐私政策', {
        confirmButtonText: '我知道了'
      })
    }
    
    // 清空所有表单数据的方法
    const clearAllForms = () => {
      Object.assign(loginForm, {
        username: '',
        password: '',
        remember: false
      })
      
      Object.assign(registerForm, {
        username: '',
        phone: '',
        email: '',
        password: '',
        confirmPassword: '',
        agreement: false
      })
    }
    
    // 初始化
    onMounted(() => {
      // 确保表单数据为空
      clearAllForms()
      
      // 从路由查询参数获取模式
      const queryMode = route.query.mode
      if (queryMode === 'register') {
        mode.value = 'register'
      }
      
      // 如果已经登录，重定向到首页
      if (store.user.isLogin) {
        router.push('/')
      }
    })
    
    return {
      mode,
      isLoading,
      loginFormRef,
      registerFormRef,
      loginForm,
      registerForm,
      loginRules,
      registerRules,
      switchMode,
      handleLogin,
      handleRegister,
      showForgotPassword,
      showTerms,
      showPrivacy,
      clearAllForms,
      // Element Plus icons
      Shop,
      User,
      Lock,
      Phone,
      Message
    }
  }
}
</script>

<style scoped>
.auth-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.auth-container {
  width: 100%;
  max-width: 420px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.auth-header {
  text-align: center;
  padding: 40px 40px 0;
}

.logo {
  margin-bottom: 30px;
}

.logo h1 {
  margin: 10px 0 0;
  font-size: 1.8rem;
  color: #333;
  font-weight: bold;
}

.auth-tabs {
  display: flex;
  border-radius: 8px;
  background: #f8f9fa;
  padding: 4px;
  margin-bottom: 30px;
}

.tab-item {
  flex: 1;
  padding: 12px;
  text-align: center;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  color: #666;
}

.tab-item.active {
  background: #FF8C00;
  color: white;
  box-shadow: 0 2px 8px rgba(255, 140, 0, 0.3);
}

.auth-content {
  padding: 0 40px 40px;
}

.auth-form h2 {
  font-size: 1.6rem;
  color: #333;
  margin-bottom: 8px;
  font-weight: 600;
}

.form-subtitle {
  color: #666;
  margin-bottom: 30px;
  font-size: 0.95rem;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.auth-footer {
  text-align: center;
  margin-top: 20px;
  color: #666;
  font-size: 0.9rem;
}


/* 响应式设计 */
@media (max-width: 480px) {
  .auth-page {
    padding: 10px;
  }
  
  .auth-container {
    max-width: 100%;
  }
  
  .auth-header {
    padding-left: 20px;
    padding-right: 20px;
  }
  
  .auth-content {
    padding: 0 20px 20px;
  }
}

/* 深度选择器样式 */
:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #e4e7ed inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px #FF8C00 inset;
}

:deep(.el-button--primary) {
  background-color: #FF8C00;
  border-color: #FF8C00;
  border-radius: 8px;
  font-weight: 500;
}

:deep(.el-button--primary:hover) {
  background-color: #FFB300;
  border-color: #FFB300;
}
</style>
